const mongoose = require('mongoose');
const User = require('../models/User');
const logger = require('./logger');

class DatabaseChecker {
  
  // 检查数据库连接状态
  async checkConnection() {
    try {
      const state = mongoose.connection.readyState;
      const states = {
        0: 'disconnected',
        1: 'connected',
        2: 'connecting',
        3: 'disconnecting'
      };

      const result = {
        status: states[state] || 'unknown',
        state: state,
        host: mongoose.connection.host,
        port: mongoose.connection.port,
        name: mongoose.connection.name
      };

      logger.info('Database connection check', result);
      return result;
    } catch (error) {
      logger.error('Database connection check failed', error);
      throw error;
    }
  }

  // 检查用户表是否存在并获取统计信息
  async checkUserCollection() {
    try {
      const collections = await mongoose.connection.db.listCollections().toArray();
      const userCollection = collections.find(col => col.name === 'users');
      
      if (!userCollection) {
        logger.warn('Users collection does not exist');
        return { exists: false, count: 0 };
      }

      const count = await User.countDocuments();
      const result = {
        exists: true,
        count,
        collectionInfo: userCollection
      };

      logger.info('User collection check', result);
      return result;
    } catch (error) {
      logger.error('User collection check failed', error);
      throw error;
    }
  }

  // 测试用户查询
  async testUserQuery(identifier) {
    try {
      logger.debug('Testing user query', { identifier });
      
      const user = await User.findOne({
        $or: [
          { email: identifier.toLowerCase() },
          { username: identifier }
        ]
      }).select('-password'); // 不返回密码

      const result = {
        found: !!user,
        user: user ? {
          id: user._id,
          username: user.username,
          email: user.email,
          name: user.name,
          isActive: user.isActive,
          createdAt: user.createdAt
        } : null
      };

      logger.auth('User query test', result);
      return result;
    } catch (error) {
      logger.error('User query test failed', error, { identifier });
      throw error;
    }
  }

  // 验证密码处理逻辑
  async testPasswordVerification(identifier, password) {
    try {
      logger.debug('Testing password verification', { identifier });
      
      const user = await User.findOne({
        $or: [
          { email: identifier.toLowerCase() },
          { username: identifier }
        ]
      });

      if (!user) {
        return { found: false, passwordValid: false };
      }

      // 验证密码
      const isValid = await user.comparePassword(password);
      
      const result = {
        found: true,
        passwordValid: isValid,
        passwordHashExists: !!user.password,
        passwordHashLength: user.password ? user.password.length : 0
      };

      logger.auth('Password verification test', { 
        ...result, 
        identifier,
        // 不记录实际密码
        passwordProvided: !!password
      });

      return result;
    } catch (error) {
      logger.error('Password verification test failed', error, { identifier });
      throw error;
    }
  }

  // 检查索引
  async checkIndexes() {
    try {
      const indexes = await User.collection.getIndexes();
      const result = {
        totalIndexes: Object.keys(indexes).length,
        indexes: Object.keys(indexes)
      };

      logger.info('Database indexes check', result);
      return result;
    } catch (error) {
      logger.error('Database indexes check failed', error);
      throw error;
    }
  }

  // 性能测试
  async performanceTest() {
    try {
      const start = Date.now();
      
      // 测试简单查询
      await User.findOne().limit(1);
      const queryTime = Date.now() - start;

      // 测试聚合查询
      const aggregationStart = Date.now();
      await User.aggregate([
        { $group: { _id: null, count: { $sum: 1 } } }
      ]);
      const aggregationTime = Date.now() - aggregationStart;

      const result = {
        simpleQueryTime: queryTime,
        aggregationTime,
        timestamp: new Date()
      };

      logger.info('Database performance test', result);
      return result;
    } catch (error) {
      logger.error('Database performance test failed', error);
      throw error;
    }
  }

  // 综合健康检查
  async healthCheck() {
    try {
      const results = {
        connection: await this.checkConnection(),
        userCollection: await this.checkUserCollection(),
        indexes: await this.checkIndexes(),
        performance: await this.performanceTest()
      };

      const isHealthy = results.connection.status === 'connected' && 
                       results.userCollection.exists;

      return {
        healthy: isHealthy,
        timestamp: new Date(),
        details: results
      };
    } catch (error) {
      logger.error('Database health check failed', error);
      return {
        healthy: false,
        error: error.message,
        timestamp: new Date()
      };
    }
  }
}

module.exports = new DatabaseChecker(); 